package com.xiaoyu.base.view.list.util.diff;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DiffUtil;

import java.util.ArrayList;
import java.util.List;

class DiffPayload {

    private final static int POOL_CAPACITY = 10;
    private final static List<DiffPayload> POOL = new ArrayList<>();

    private List<?> mNewList;
    @Nullable
    private BaseDiffAdapter.OnUpdateCompleteListener mOnUpdateFinishListener;
    private DiffUtil.DiffResult mDiffResult;

    private DiffPayload(List<?> newList, @Nullable BaseDiffAdapter.OnUpdateCompleteListener onUpdateFinishListener) {
        this.mNewList = newList;
        this.mOnUpdateFinishListener = onUpdateFinishListener;
    }

    static DiffPayload obtain(List<?> newList, @Nullable BaseDiffAdapter.OnUpdateCompleteListener onUpdateFinishListener) {
        synchronized (POOL) {
            int size = POOL.size();
            if (size > 0) {
                DiffPayload payload = POOL.remove(size - 1);
                payload.mNewList = newList;
                payload.mOnUpdateFinishListener = onUpdateFinishListener;
                return payload;
            }
        }
        return new DiffPayload(newList, onUpdateFinishListener);
    }

    static void release(DiffPayload payload) {
        payload.mNewList = null;
        payload.mOnUpdateFinishListener = null;
        payload.mDiffResult = null;

        synchronized (POOL) {
            if (POOL.size() < POOL_CAPACITY) {
                POOL.add(payload);
            }
        }
    }

    List<?> getNewList() {
        return mNewList;
    }

    @Nullable
    BaseDiffAdapter.OnUpdateCompleteListener getOnUpdateFinishListener() {
        return mOnUpdateFinishListener;
    }

    DiffUtil.DiffResult getDiffResult() {
        return mDiffResult;
    }

    void setDiffResult(DiffUtil.DiffResult diffResult) {
        mDiffResult = diffResult;
    }
}
